import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from './router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)
  // 用户是否已经登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.userId
      if (hasGetUserInfo) {
        next() // 允许通行
      } else {
        try {
          // 获取用户信息
          const {
            roles: { menus }
          } = await store.dispatch('user/getInfo')
          console.log(menus) // menus是当前用户拥有的权限标识
          const filterRoutes = asyncRoutes.filter((item) => menus.includes(item.name)) // 根据权限标识筛选出用户能访问的动态路由
          router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 动态添加可访问路由表
          // 因为addRoutes方法添加的路由不是响应式的，所以我们利用vuex来解决左侧菜单的显示问题
          store.commit('user/SET_ROUTES', filterRoutes)
          next(to.path)
        } catch (error) {
          // 如果获取用户信息出错：删除token 并跳转到登录页
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 用户没有登录的情况下，判断目标路由是不是在白名单里
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
